Online-Academy
Look, Read, Understand, Apply

Data Structure

Algorithm Analysis - I

  1. The TimerUtil class
    • This class contains a single method (measureTime) whose job is:
    • Start a timer
    • Run the code you want to measure
    • Stop the timer
    • Return the time taken
    • Think of it like a stopwatch:
    • You give it some code -> it tells you how long it took.
      class TimerUtil {
          // This method accepts any code block using Runnable
          public static long measureTime(Runnable task) {
              long start = System.nanoTime();
              task.run();
              long end = System.nanoTime();
              return end - start;
          }
      }
      
  2. The main program
    class CheckRunTime{
        public static void main(String[] args) {
            long duration = TimerUtil.measureTime(() -> {
                long sum = 0;
                for (long i = 1; i < 9000000; i++) {
                    sum += i;
                }
                System.out.println("Sum = " + sum);
            });
            System.out.println("Time (ns): " + duration);
            System.out.println("Time (ms): " + duration / 1_000_000.0);  
        }
    }    
    
    • In the main class, we call the TimerUtil.measureTime(...) method and give it the algorithm we want to test.
    • In this example, the algorithm is just adding numbers from 1 to 9000000.
    • The timer measures how long that loop takes and gives the duration back.
    • Then we print the result in nanoseconds and milliseconds.
  3. Why this is useful?
    • You can test any algorithm (sorting, searching, loops, etc.) using the same timing method.
    • The main program stays clean and easy to read.
    • You won't repeat timing code everywhere - just reuse measureTime().